package com.carrent.sxt.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.apache.ibatis.annotations.ResultMap;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.EnumMap;

/**
 * 解析二维码
 */
public class ZXingCodeDecodeUtils {


    //二维码格式参数-----写法固定
    private static final EnumMap<DecodeHintType, Object> hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);

    static {
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
    }

    /**
     * 解析文件
     *
     * @param path
     */
    public static String decodeCodeFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            //将文件转成图片对象
            try {
                String content = decodeCodeStream(new FileInputStream(file));
                return content;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 解析流
     *
     * @param inputStream
     */
    public static String decodeCodeStream(InputStream inputStream) {
        if (null != inputStream) {
            try {
                BufferedImage image = ImageIO.read(inputStream);
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                Binarizer binarizer = new HybridBinarizer(source);
                BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
                MultiFormatReader reader = new MultiFormatReader();
                Result result = reader.decode(binaryBitmap, hints);
                String content = result.getText();
                return content;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    public static void main(String[] args) throws FileNotFoundException {
//        String string = decodeCodeFile("F:/yanghu.gif");
        String string = decodeCodeStream(new FileInputStream(new File("F:/yanghu.gif")));
        System.out.println(string);
    }
}